package com.chart.web.controller.common.ai;

import com.alipay.easysdk.kms.aliyun.models.RuntimeOptions;
import com.aliyun.imagerecog20190930.models.RecognizeImageColorRequest;
import com.aliyun.imagerecog20190930.models.RecognizeImageColorResponse;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.tea.TeaException;
import com.aliyun.tea.TeaModel;
import com.aliyun.teautil.Common;
import com.chart.common.core.domain.AjaxResult;
import com.chart.common.core.domain.entity.SysUser;
import com.chart.common.core.domain.entity.UserCoinLog;
import com.chart.common.utils.ColorUtils;
import com.chart.common.utils.SecurityUtils;
import com.chart.common.utils.StringUtils;
import com.chart.system.service.ISysUserService;
import com.chart.system.service.IUserCoinLogsService;
import com.chart.web.controller.chart.dto.ImageColorDTO;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import static com.chart.framework.datasource.DynamicDataSourceContextHolder.log;

/**
 * 阿里 视觉智能开放平台图像颜色识别
 */
@RestController
@RequestMapping("/recognizeImageColor")
public class RecognizeColorController {

    @Value("${aliyun.oss.endpoint}")
    private String endpoint;

    @Value("${aliyun.oss.accessKeyId}")
    private String accessKeyId;

    @Value("${aliyun.oss.accessKeySecret}")
    private String accessKeySecret;

    @Value("${aliyun.oss.bucketName}")
    private String bucketName;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private IUserCoinLogsService userCoinLogsService;

    /**
     * 创建阿里云客户端实例
     */
    private com.aliyun.imagerecog20190930.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                .setAccessKeyId(accessKeyId)
                .setAccessKeySecret(accessKeySecret);
        config.endpoint = "imagerecog.cn-shanghai.aliyuncs.com";  // 图像识别服务的 endpoint
        return new com.aliyun.imagerecog20190930.Client(config);
    }

/*
    @PostMapping("/analyze")
    public AjaxResult analyzeImageColor(@RequestParam Integer totalColors, @RequestParam("file") MultipartFile file,Integer number)
            throws IOException {

        if(number<2){
            return new AjaxResult(603, "上传的颜色的数量需要大于2，请重新上传");
        }
        if (totalColors == null) {
            log.warn("上传颜色数量为空");
            return new AjaxResult(603, "上传颜色数量为空");
        }

        if (ObjectUtils.isEmpty(file)) {
            log.warn("上传文件为空");
            return new AjaxResult(603, "上传文件为空");
        }

        // 校验文件格式（PNG、JPG、JPEG、BMP）
        List<String> allowedFormats = Arrays.asList("PNG", "JPG", "JPEG", "BMP");
        String fileExtension = FilenameUtils.getExtension(file.getOriginalFilename()).toUpperCase();
        if (!allowedFormats.contains(fileExtension)) {
            log.warn("文件格式不支持: {}", fileExtension);
            return new AjaxResult(601, "仅支持 PNG、JPG、JPEG、BMP 格式的图片");
        }

        // 检查并调整图像尺寸
        BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
        int width = bufferedImage.getWidth();
        int height = bufferedImage.getHeight();

        // 如果图片宽度或高度大于1080，则进行调整
        if (width > 1080 || height > 1080) {
            bufferedImage = Thumbnails.of(bufferedImage)
                    .size(1080, 1080) // 设置最大宽高为 1080
                    .outputQuality(0.85) // 设置质量，进一步压缩
                    .asBufferedImage();
            log.info("图片分辨率超出限制，已调整尺寸至 1080 像素以内");
        }

        // 将调整后的图像写入 ByteArrayOutputStream 中以检查文件大小
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(bufferedImage, fileExtension.toLowerCase(), outputStream);  // 假设图像格式与上传文件一致
        byte[] imageBytes = outputStream.toByteArray();
        outputStream.close();

           // 校验调整后的文件大小不超过1MB
        long maxFileSize = 1 * 1024 * 1024 + 512 * 1024; // 1MB + 512KB 的缓冲
        if (imageBytes.length > maxFileSize) {
            log.warn("调整后的文件大小超过限制，文件大小: {} bytes", imageBytes.length);
            return new AjaxResult(602, "调整后的图片大小仍超过1M，请上传更小的图片！");
        }

          // 使用 ByteArrayInputStream 将压缩后的图像字节作为输入流
        ByteArrayInputStream inputStream = new ByteArrayInputStream(imageBytes);



        // 创建 OSS 客户端实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        String uniqueFileName = "uploads/" + System.currentTimeMillis() + "_" + file.getOriginalFilename();

        try {
            // 上传文件到 OSS
            ossClient.putObject(bucketName, uniqueFileName, inputStream);
            // 设置文件为公共读
            ossClient.setObjectAcl(bucketName, uniqueFileName, CannedAccessControlList.PublicRead);

            // 构造图片 URL
            String imageUrl = "https://" + bucketName + "." + endpoint + "/" + uniqueFileName;
            log.info("上传文件 URL: {}", imageUrl);

            // 使用阿里云客户端创建请求
            com.aliyun.imagerecog20190930.Client client = createClient(accessKeyId, accessKeySecret);
            com.aliyun.imagerecog20190930.models.RecognizeImageColorRequest request = new com.aliyun.imagerecog20190930.models.RecognizeImageColorRequest()
                    .setUrl(imageUrl)
                    .setColorCount(number);  // 使用传入的 totalColors 参数
            com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();

            // 发送请求并接收响应
            RecognizeImageColorResponse response = client.recognizeImageColorWithOptions(request, runtime);
            String jsonResponse = com.aliyun.teautil.Common.toJSONString(TeaModel.buildMap(response));

            // 解析返回结果
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode = objectMapper.readTree(jsonResponse);


            List<String> colors = new ArrayList<>();
            JsonNode colorTemplateList = jsonNode.path("body").path("Data").path("ColorTemplateList");
            System.out.println(colorTemplateList);
            // 提取颜色数据
            for (JsonNode colorNode : colorTemplateList) {
                String color = "#" + colorNode.path("Color").asText();  // 添加 "#" 前缀
                colors.add(color);

            }

             List<String> arithmeticColors = ColorUtils.generateGradientColors(colors, totalColors);
            if (arithmeticColors.isEmpty()) {
                return AjaxResult.warn("获取过渡色异常");
            }

            // 返回结果
            HashMap<Object, Object> map = new HashMap<>();
            map.put("colors", colors);
            map.put("arithmeticColors", arithmeticColors);

            log.info("识别的颜色: {}", colors);
            return AjaxResult.success(map);

        } catch (TeaException e) {
            log.error("阿里云 API 调用失败: {}", e.getMessage(), e);
            return AjaxResult.error("阿里云 API 调用失败: " + e.getMessage());
        } catch (Exception e) {
            log.error("文件上传或处理失败: {}", e.getMessage(), e);
            return AjaxResult.error("上传或处理文件失败: " + e.getMessage());
        } finally {
            // 确保关闭 OSS 客户端
            if (ossClient != null) {
                try {
                    // 删除 OSS 中的文件
                    ossClient.deleteObject(bucketName, uniqueFileName);
                    log.info("已删除 OSS 中的文件: {}", uniqueFileName);
                } catch (Exception deleteException) {
                    log.warn("删除 OSS 文件失败: {}", deleteException.getMessage());
                }
                ossClient.shutdown();
            }
            inputStream.close();
        }
    }
*/

/*
 牛逼   @PostMapping("/analyze")
    public AjaxResult analyzeImageColor(@RequestParam Integer totalColors, @RequestParam("file") MultipartFile file, Integer number)
            throws IOException {

        if (number>16 ||  number < 2 ) {
            return new AjaxResult(603, "上传的颜色数量超出范围，要求在2-16之间，请重新上传");
        }
        if (totalColors == null) {
            log.warn("上传颜色数量为空");
            return new AjaxResult(603, "上传颜色数量为空");
        }

        if (ObjectUtils.isEmpty(file)) {
            log.warn("上传文件为空");
            return new AjaxResult(603, "上传文件为空");
        }

        // 校验文件格式（PNG、JPG、JPEG、BMP）
        List<String> allowedFormats = Arrays.asList("PNG", "JPG", "JPEG", "BMP");
        String fileExtension = FilenameUtils.getExtension(file.getOriginalFilename()).toUpperCase();
        if (!allowedFormats.contains(fileExtension)) {
            log.warn("文件格式不支持: {}", fileExtension);
            return new AjaxResult(601, "仅支持 PNG、JPG、JPEG、BMP 格式的图片");
        }

        // 检查并调整图像尺寸
        BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
        int width = bufferedImage.getWidth();
        int height = bufferedImage.getHeight();

        // 如果图片宽度或高度大于1080，则进行调整
        if (width > 1080 || height > 1080) {
            bufferedImage = Thumbnails.of(bufferedImage)
                    .size(1080, 1080) // 设置最大宽高为 1080
                    .outputQuality(0.85) // 设置质量，进一步压缩
                    .asBufferedImage();
            log.info("图片分辨率超出限制，已调整尺寸至 1080 像素以内");
        }

        // 将调整后的图像写入 ByteArrayOutputStream 中以检查文件大小
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(bufferedImage, fileExtension.toLowerCase(), outputStream);  // 假设图像格式与上传文件一致
        byte[] imageBytes = outputStream.toByteArray();
       // outputStream.close();


        // 校验调整后的文件大小不超过1MB
        long maxFileSize = 1 * 1024 * 1024 + 512 * 1024; // 1MB + 512KB 的缓冲
        if (imageBytes.length > maxFileSize) {
            log.warn("调整后的文件大小超过限制，文件大小: {} bytes", imageBytes.length);
            return new AjaxResult(602, "调整后的图片大小仍超过1M，请上传更小的图片！");
        }

        // 使用 ByteArrayInputStream 将压缩后的图像字节作为输入流
        ByteArrayInputStream inputStream = new ByteArrayInputStream(imageBytes);

        // 创建 OSS 客户端实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        String uniqueFileName = "uploads/" + System.currentTimeMillis() + "_" + file.getOriginalFilename();

       // outputStream.close();
       // file.getInputStream().close();
        try {
            // 上传文件到 OSS
            ossClient.putObject(bucketName, uniqueFileName, inputStream);
            // 设置文件为公共读
            ossClient.setObjectAcl(bucketName, uniqueFileName, CannedAccessControlList.PublicRead);

            // 构造图片 URL
            String imageUrl = "https://" + bucketName + "." + endpoint + "/" + uniqueFileName;
            log.info("上传文件 URL: {}", imageUrl);

            // 使用阿里云客户端创建请求
            com.aliyun.imagerecog20190930.Client client = createClient(accessKeyId, accessKeySecret);

            // 第一次调用阿里云的颜色识别接口
            com.aliyun.imagerecog20190930.models.RecognizeImageColorRequest request1 = new com.aliyun.imagerecog20190930.models.RecognizeImageColorRequest()
                    .setUrl(imageUrl)
                    .setColorCount(number);  // 使用传入的 totalColors 参数
            com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();

            // 发送第一次请求并接收响应
            RecognizeImageColorResponse response1 = client.recognizeImageColorWithOptions(request1, runtime);
            String jsonResponse1 = com.aliyun.teautil.Common.toJSONString(TeaModel.buildMap(response1));

            // 解析第一次返回结果
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode1 = objectMapper.readTree(jsonResponse1);

            List<String> colors = new ArrayList<>();
            JsonNode colorTemplateList1 = jsonNode1.path("body").path("Data").path("ColorTemplateList");
            for (JsonNode colorNode : colorTemplateList1) {
                String color = "#" + colorNode.path("Color").asText();  // 添加 "#" 前缀
                colors.add(color);
            }

            // 第二次调用阿里云的颜色识别接口
            com.aliyun.imagerecog20190930.models.RecognizeImageColorRequest request2 = new com.aliyun.imagerecog20190930.models.RecognizeImageColorRequest()
                    .setUrl(imageUrl)
                    .setColorCount(6); // 使用传入的 totalColors 参数

            // 发送第二次请求并接收响应
            RecognizeImageColorResponse response2 = client.recognizeImageColorWithOptions(request2, runtime);
            String jsonResponse2 = com.aliyun.teautil.Common.toJSONString(TeaModel.buildMap(response2));

            // 解析第二次返回结果
            JsonNode jsonNode2 = objectMapper.readTree(jsonResponse2);

            List<String> colors2 = new ArrayList<>();
            JsonNode colorTemplateList2 = jsonNode2.path("body").path("Data").path("ColorTemplateList");
            for (JsonNode colorNode : colorTemplateList2) {
                String color = "#" + colorNode.path("Color").asText();  // 添加 "#" 前缀
                colors2.add(color);
            }

            List<String> arithmeticColors = ColorUtils.generateGradientColors(colors, totalColors);
            if (arithmeticColors.isEmpty()) {
                return AjaxResult.warn("获取过渡色异常");
            }

            // 返回结果
            HashMap<Object, Object> map = new HashMap<>();
            map.put("colors", colors);
            map.put("colors2", colors2);
            map.put("arithmeticColors", arithmeticColors);

            log.info("识别的颜色: {}", colors);
            log.info("第二次识别的颜色: {}", colors2);

            inputStream.close();
            outputStream.close();
            file.getInputStream().close();
            return AjaxResult.success(map);

        } catch (TeaException e) {
            log.error("阿里云 API 调用失败: {}", e.getMessage(), e);
            return AjaxResult.error("阿里云 API 调用失败: " + e.getMessage());
        } catch (Exception e) {
            log.error("文件上传或处理失败: {}", e.getMessage(), e);
            return AjaxResult.error("上传或处理文件失败: " + e.getMessage());
        } finally {
            // 确保关闭 OSS 客户端
            if (ossClient != null) {
                try {
                    // 删除 OSS 中的文件
                    ossClient.deleteObject(bucketName, uniqueFileName);
                    log.info("已删除 OSS 中的文件: {}", uniqueFileName);
                } catch (Exception deleteException) {
                    log.warn("删除 OSS 文件失败: {}", deleteException.getMessage());
                }
                ossClient.shutdown();
            }

        }
    }
*/


    @PostMapping("/analyze")
    public AjaxResult analyzeImageColor(@RequestParam Integer totalColors, @RequestParam("file") MultipartFile file, Integer number) throws IOException {
        if (number > 16 || number < 2) {
            return new AjaxResult(603, "上传的颜色数量超出范围，要求在2-16之间，请重新上传");
        }
        if (totalColors == null) {
            log.warn("上传颜色数量为空");
            return new AjaxResult(603, "上传颜色数量为空");
        }

        if (ObjectUtils.isEmpty(file)) {
            log.warn("上传文件为空");
            return new AjaxResult(603, "上传文件为空");
        }

        List<String> allowedFormats = Arrays.asList("PNG", "JPG", "JPEG", "BMP");
        String fileExtension = FilenameUtils.getExtension(file.getOriginalFilename()).toUpperCase();
        if (!allowedFormats.contains(fileExtension)) {
            log.warn("文件格式不支持: {}", fileExtension);
            return new AjaxResult(601, "仅支持 PNG、JPG、JPEG、BMP 格式的图片");
        }

        try (InputStream fis = file.getInputStream()) {
            BufferedImage bufferedImage = ImageIO.read(fis);
            int width = bufferedImage.getWidth();
            int height = bufferedImage.getHeight();

            if (width > 1080 || height > 1080) {
                bufferedImage = Thumbnails.of(bufferedImage)
                        .size(1080, 1080)
                        .outputQuality(0.85)
                        .asBufferedImage();
                log.info("图片分辨率超出限制，已调整尺寸至 1080 像素以内");
            }

            try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
                ImageIO.write(bufferedImage, fileExtension.toLowerCase(), outputStream);
                byte[] imageBytes = outputStream.toByteArray();

                long maxFileSize = 1 * 1024 * 1024 + 512 * 1024;
                if (imageBytes.length > maxFileSize) {
                    log.warn("调整后的文件大小超过限制，文件大小: {} bytes", imageBytes.length);
                    return new AjaxResult(602, "调整后的图片大小仍超过1M，请上传更小的图片！");
                }

                try (ByteArrayInputStream inputStream = new ByteArrayInputStream(imageBytes)) {
                    OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
                    String uniqueFileName = "uploads/" + System.currentTimeMillis() + "_" + file.getOriginalFilename();
                    try {
                        ossClient.putObject(bucketName, uniqueFileName, inputStream);
                        ossClient.setObjectAcl(bucketName, uniqueFileName, CannedAccessControlList.PublicRead);

                        String imageUrl = "https://" + bucketName + "." + endpoint + "/" + uniqueFileName;
                        log.info("上传文件 URL: {}", imageUrl);

                        com.aliyun.imagerecog20190930.Client client = createClient(accessKeyId, accessKeySecret);
                        RecognizeImageColorResponse response1 = client.recognizeImageColorWithOptions(
                                new com.aliyun.imagerecog20190930.models.RecognizeImageColorRequest()
                                        .setUrl(imageUrl)
                                        .setColorCount(number),
                                new com.aliyun.teautil.models.RuntimeOptions());

                        // 解析第一次返回结果
                        ObjectMapper objectMapper = new ObjectMapper();
                        JsonNode jsonNode1 = objectMapper.readTree(com.aliyun.teautil.Common.toJSONString(TeaModel.buildMap(response1)));
                        List<String> colors = extractColors(jsonNode1);

                        RecognizeImageColorResponse response2 = client.recognizeImageColorWithOptions(
                                new com.aliyun.imagerecog20190930.models.RecognizeImageColorRequest()
                                        .setUrl(imageUrl)
                                        .setColorCount(6),
                                new com.aliyun.teautil.models.RuntimeOptions());

                        // 解析第二次返回结果
                        JsonNode jsonNode2 = objectMapper.readTree(com.aliyun.teautil.Common.toJSONString(TeaModel.buildMap(response2)));
                        List<String> colors2 = extractColors(jsonNode2);

                        List<String> arithmeticColors = ColorUtils.generateGradientColors(colors, totalColors);
                        if (arithmeticColors.isEmpty()) {
                            return AjaxResult.warn("获取过渡色异常");
                        }

                        HashMap<Object, Object> map = new HashMap<>();
                        map.put("colors", colors);
                        map.put("colors2", colors2);
                        map.put("arithmeticColors", arithmeticColors);

                        log.info("识别的颜色: {}", colors);
                        log.info("第二次识别的颜色: {}", colors2);

                        return AjaxResult.success(map);
                    } finally {
                        if (ossClient != null) {
                            try {
                                ossClient.deleteObject(bucketName, uniqueFileName);
                                log.info("已删除 OSS 中的文件: {}", uniqueFileName);
                            } catch (Exception deleteException) {
                                log.warn("删除 OSS 文件失败: {}", deleteException.getMessage());
                            }
                            ossClient.shutdown();
                        }
                    }
                }
            }
        } catch (TeaException e) {
            log.error("阿里云 API 调用失败: {}", e.getMessage(), e);
            return AjaxResult.error("阿里云 API 调用失败: " + e.getMessage());
        } catch (Exception e) {
            log.error("文件上传或处理失败: {}", e.getMessage(), e);
            return AjaxResult.error("上传或处理文件失败: " + e.getMessage());
        }
    }

    private List<String> extractColors(JsonNode jsonNode) {
        List<String> colors = new ArrayList<>();
        JsonNode colorTemplateList = jsonNode.path("body").path("Data").path("ColorTemplateList");
        for (JsonNode colorNode : colorTemplateList) {
            String color = "#" + colorNode.path("Color").asText();  // 添加 "#" 前缀
            colors.add(color);
        }
        return colors;
    }


    /**
     * @param totalColors
     * @param file
     * @param number
     * @return
     * @throws IOException
     */
/*
    @PostMapping("/analyzePhotos")
    @Transactional
    public AjaxResult analyzePhotos(@RequestParam Integer totalColors, @RequestParam("file") MultipartFile file, Integer number)
            throws IOException {
        if (number > 16 || number < 2) {
            return new AjaxResult(603, "上传的颜色数量超出范围，要求在2-16之间，请重新上传");
        }
        if (totalColors == null) {
            log.warn("上传颜色数量为空");
            return new AjaxResult(603, "上传颜色数量为空");
        }

        if (ObjectUtils.isEmpty(file)) {
            log.warn("上传文件为空");
            return new AjaxResult(603, "上传文件为空");
        }

        // 校验文件格式（PNG、JPG、JPEG、BMP）
        List<String> allowedFormats = Arrays.asList("PNG", "JPG", "JPEG", "BMP");
        String fileExtension = FilenameUtils.getExtension(file.getOriginalFilename()).toUpperCase();
        if (!allowedFormats.contains(fileExtension)) {
            log.warn("文件格式不支持: {}", fileExtension);
            return new AjaxResult(601, "仅支持 PNG、JPG、JPEG、BMP 格式的图片");
        }

        // 检查并调整图像尺寸
        BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
        int width = bufferedImage.getWidth();
        int height = bufferedImage.getHeight();

        file.getInputStream().close();//新加
        // 如果图片宽度或高度大于1080，则进行调整
        if (width > 1080 || height > 1080) {
            bufferedImage = Thumbnails.of(bufferedImage)
                    .size(1080, 1080) // 设置最大宽高为 1080
                    .outputQuality(0.85) // 设置质量，进一步压缩
                    .asBufferedImage();
            log.info("图片分辨率超出限制，已调整尺寸至 1080 像素以内");
        }

        // 将调整后的图像写入 ByteArrayOutputStream 中以检查文件大小
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(bufferedImage, fileExtension.toLowerCase(), outputStream);  // 假设图像格式与上传文件一致
        byte[] imageBytes = outputStream.toByteArray();
        outputStream.close();


        // 校验调整后的文件大小不超过1MB
        long maxFileSize = 1 * 1024 * 1024 + 512 * 1024; // 1MB + 512KB 的缓冲
        if (imageBytes.length > maxFileSize) {
            log.warn("调整后的文件大小超过限制，文件大小: {} bytes", imageBytes.length);
            return new AjaxResult(602, "调整后的图片大小仍超过1M，请上传更小的图片！");
        }

        // 使用 ByteArrayInputStream 将压缩后的图像字节作为输入流
        ByteArrayInputStream inputStream = new ByteArrayInputStream(imageBytes);

        // 创建 OSS 客户端实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        String uniqueFileName = "uploads/" + System.currentTimeMillis() + "_" + file.getOriginalFilename();

        Long userId = SecurityUtils.getUserId();
        SysUser sysUser = userService.queryById(userId);
        Integer isVip = sysUser.getIsVip();
        Integer totalCoins = userCoinLogsService.getTotalCoinsByUserId(userId);
        if (isVip == 0) {
            Integer coins = 1;//解图
            String type = "aiColorDeduct";
            if (totalCoins - coins < 0) {          //金币不足
                // 构建返回数据
                HashMap<Object, Object> data = new HashMap<>();
                data.put("deductAiCoins", 0);
                data.put("totalCoins", totalCoins);
                data.put("deductStatus", 0);//扣除失败
                data.put("colors", "");
                data.put("colors2", "");
                data.put("arithmeticColors", "");
                return AjaxResult.success("金币不足", data);
            } else {
                // 扣除金币
                UserCoinLog log = new UserCoinLog();
                log.setUserId(userId);
                log.setAction(type);
                log.setCoins(-coins); // 扣除金币数，使用负值表示扣除
                log.setCreatedAt(LocalDateTime.now());
                userCoinLogsService.save(log);

                try {
                    // 上传文件到 OSS
                    ossClient.putObject(bucketName, uniqueFileName, inputStream);
                    // 设置文件为公共读
                    ossClient.setObjectAcl(bucketName, uniqueFileName, CannedAccessControlList.PublicRead);

                    // 构造图片 URL
                    String imageUrl = "https://" + bucketName + "." + endpoint + "/" + uniqueFileName;

                    // 使用阿里云客户端创建请求
                    com.aliyun.imagerecog20190930.Client client = createClient(accessKeyId, accessKeySecret);

                    // 第一次调用阿里云的颜色识别接口
                    com.aliyun.imagerecog20190930.models.RecognizeImageColorRequest request1 = new com.aliyun.imagerecog20190930.models.RecognizeImageColorRequest()
                            .setUrl(imageUrl)
                            .setColorCount(number);  // 使用传入的 totalColors 参数
                    com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();

                    // 发送第一次请求并接收响应
                    RecognizeImageColorResponse response1 = client.recognizeImageColorWithOptions(request1, runtime);
                    String jsonResponse1 = com.aliyun.teautil.Common.toJSONString(TeaModel.buildMap(response1));

                    // 解析第一次返回结果
                    ObjectMapper objectMapper = new ObjectMapper();
                    JsonNode jsonNode1 = objectMapper.readTree(jsonResponse1);

                    List<String> colors = new ArrayList<>();
                    JsonNode colorTemplateList1 = jsonNode1.path("body").path("Data").path("ColorTemplateList");
                    for (JsonNode colorNode : colorTemplateList1) {
                        String color = "#" + colorNode.path("Color").asText();  // 添加 "#" 前缀
                        colors.add(color);
                    }

                    // 第二次调用阿里云的颜色识别接口
                    com.aliyun.imagerecog20190930.models.RecognizeImageColorRequest request2 = new com.aliyun.imagerecog20190930.models.RecognizeImageColorRequest()
                            .setUrl(imageUrl)
                            .setColorCount(6); // 使用传入的 totalColors 参数

                    // 发送第二次请求并接收响应
                    RecognizeImageColorResponse response2 = client.recognizeImageColorWithOptions(request2, runtime);
                    String jsonResponse2 = com.aliyun.teautil.Common.toJSONString(TeaModel.buildMap(response2));

                    // 解析第二次返回结果
                    JsonNode jsonNode2 = objectMapper.readTree(jsonResponse2);

                    List<String> colors2 = new ArrayList<>();
                    JsonNode colorTemplateList2 = jsonNode2.path("body").path("Data").path("ColorTemplateList");
                    for (JsonNode colorNode : colorTemplateList2) {
                        String color = "#" + colorNode.path("Color").asText();  // 添加 "#" 前缀
                        colors2.add(color);
                    }

                    List<String> arithmeticColors = ColorUtils.generateGradientColors(colors, totalColors);
                    if (arithmeticColors.isEmpty()) {
                        return AjaxResult.warn("获取过渡色异常");
                    }


                    // 返回结果
                    HashMap<Object, Object> map1 = new HashMap<>();
                    map1.put("colors", colors);
                    map1.put("colors2", colors2);
                    map1.put("arithmeticColors", arithmeticColors);
                    map1.put("deductAiCoins", coins);
                    map1.put("totalCoins", totalCoins);
                    map1.put("deductStatus", 1);//扣除成功

                    return AjaxResult.success(map1);

                } catch (TeaException e) {
                    return AjaxResult.error("阿里云 API 调用失败: " + e.getMessage());
                } catch (Exception e) {
                    return AjaxResult.error("上传或处理文件失败: " + e.getMessage());
                } finally {
                    // 确保关闭 OSS 客户端
                    if (ossClient != null) {
                        try {
                            // 删除 OSS 中的文件
                            ossClient.deleteObject(bucketName, uniqueFileName);
                        } catch (Exception deleteException) {
                        }
                        ossClient.shutdown();
                    }
                    inputStream.close();
                }


            }
        }


        try {
            // 上传文件到 OSS
            ossClient.putObject(bucketName, uniqueFileName, inputStream);
            // 设置文件为公共读
            ossClient.setObjectAcl(bucketName, uniqueFileName, CannedAccessControlList.PublicRead);

            // 构造图片 URL
            String imageUrl = "https://" + bucketName + "." + endpoint + "/" + uniqueFileName;
            log.info("上传文件 URL: {}", imageUrl);

            // 使用阿里云客户端创建请求
            com.aliyun.imagerecog20190930.Client client = createClient(accessKeyId, accessKeySecret);

            // 第一次调用阿里云的颜色识别接口
            com.aliyun.imagerecog20190930.models.RecognizeImageColorRequest request1 = new com.aliyun.imagerecog20190930.models.RecognizeImageColorRequest()
                    .setUrl(imageUrl)
                    .setColorCount(number);  // 使用传入的 totalColors 参数
            com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();

            // 发送第一次请求并接收响应
            RecognizeImageColorResponse response1 = client.recognizeImageColorWithOptions(request1, runtime);
            String jsonResponse1 = com.aliyun.teautil.Common.toJSONString(TeaModel.buildMap(response1));

            // 解析第一次返回结果
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode1 = objectMapper.readTree(jsonResponse1);

            List<String> colors = new ArrayList<>();
            JsonNode colorTemplateList1 = jsonNode1.path("body").path("Data").path("ColorTemplateList");
            for (JsonNode colorNode : colorTemplateList1) {
                String color = "#" + colorNode.path("Color").asText();  // 添加 "#" 前缀
                colors.add(color);
            }

            // 第二次调用阿里云的颜色识别接口
            com.aliyun.imagerecog20190930.models.RecognizeImageColorRequest request2 = new com.aliyun.imagerecog20190930.models.RecognizeImageColorRequest()
                    .setUrl(imageUrl)
                    .setColorCount(6); // 使用传入的 totalColors 参数

            // 发送第二次请求并接收响应
            RecognizeImageColorResponse response2 = client.recognizeImageColorWithOptions(request2, runtime);
            String jsonResponse2 = com.aliyun.teautil.Common.toJSONString(TeaModel.buildMap(response2));

            // 解析第二次返回结果
            JsonNode jsonNode2 = objectMapper.readTree(jsonResponse2);

            List<String> colors2 = new ArrayList<>();
            JsonNode colorTemplateList2 = jsonNode2.path("body").path("Data").path("ColorTemplateList");
            for (JsonNode colorNode : colorTemplateList2) {
                String color = "#" + colorNode.path("Color").asText();  // 添加 "#" 前缀
                colors2.add(color);
            }

            List<String> arithmeticColors = ColorUtils.generateGradientColors(colors, totalColors);
            if (arithmeticColors.isEmpty()) {
                return AjaxResult.warn("获取过渡色异常");
            }


            // 返回结果
            HashMap<Object, Object> map = new HashMap<>();
            map.put("colors", colors);
            map.put("colors2", colors2);
            map.put("arithmeticColors", arithmeticColors);
            map.put("deductAiCoins", 0);
            map.put("totalCoins", totalCoins);
            map.put("deductStatus", 0);//扣除失败


            log.info("识别的颜色: {}", colors);
            log.info("第二次识别的颜色: {}", colors2);
            return AjaxResult.success(map);

        } catch (TeaException e) {
            log.error("阿里云 API 调用失败: {}", e.getMessage(), e);
            return AjaxResult.error("阿里云 API 调用失败: " + e.getMessage());
        } catch (Exception e) {
            log.error("文件上传或处理失败: {}", e.getMessage(), e);
            return AjaxResult.error("上传或处理文件失败: " + e.getMessage());
        } finally {
            // 确保关闭 OSS 客户端
            if (ossClient != null) {
                try {
                    // 删除 OSS 中的文件
                    ossClient.deleteObject(bucketName, uniqueFileName);
                    log.info("已删除 OSS 中的文件: {}", uniqueFileName);
                } catch (Exception deleteException) {
                    log.warn("删除 OSS 文件失败: {}", deleteException.getMessage());
                }
                ossClient.shutdown();
            }
            inputStream.close();
        }
    }
*/


    @PostMapping("/analyze/photo")
    public AjaxResult analyzeImageColorPhoto(@RequestParam Integer totalColors, @RequestParam("file") MultipartFile file, Integer number) throws IOException {
        if (number > 16 || number < 2) {
            return new AjaxResult(603, "上传的颜色数量超出范围，要求在2-16之间，请重新上传");
        }
        if (totalColors == null) {
            log.warn("上传颜色数量为空");
            return new AjaxResult(603, "上传颜色数量为空");
        }

        if (ObjectUtils.isEmpty(file)) {
            log.warn("上传文件为空");
            return new AjaxResult(603, "上传文件为空");
        }

        List<String> allowedFormats = Arrays.asList("PNG", "JPG", "JPEG", "BMP");
        String fileExtension = FilenameUtils.getExtension(file.getOriginalFilename()).toUpperCase();
        if (!allowedFormats.contains(fileExtension)) {
            log.warn("文件格式不支持: {}", fileExtension);
            return new AjaxResult(601, "仅支持 PNG、JPG、JPEG、BMP 格式的图片");
        }
        Long userId = SecurityUtils.getUserId();
        SysUser sysUser = userService.queryById(userId);
        Integer isVip = sysUser.getIsVip();
        Integer totalCoins = userCoinLogsService.getTotalCoinsByUserId(userId);
        if (isVip == 0) {
            Integer coins = 1;//解图
            String type = "aiColorDeduct";
            if (totalCoins - coins < 0) {          //金币不足
                // 构建返回数据
                HashMap<Object, Object> data = new HashMap<>();
                data.put("deductAiCoins", 0);
                data.put("totalCoins", totalCoins);
                data.put("deductStatus", 0);//扣除失败

                data.put("colors", "");
                data.put("colors2", "");
                data.put("arithmeticColors", "");
                return AjaxResult.success("金币不足", data);
            } else {
                // 扣除金币
                UserCoinLog log = new UserCoinLog();
                log.setUserId(userId);
                log.setAction(type);
                log.setCoins(-coins); // 扣除金币数，使用负值表示扣除
                log.setCreatedAt(LocalDateTime.now());
                userCoinLogsService.save(log);


                try (InputStream fis = file.getInputStream()) {
                    BufferedImage bufferedImage = ImageIO.read(fis);
                    int width = bufferedImage.getWidth();
                    int height = bufferedImage.getHeight();

                    if (width > 1080 || height > 1080) {
                        bufferedImage = Thumbnails.of(bufferedImage)
                                .size(1080, 1080)
                                .outputQuality(0.85)
                                .asBufferedImage();
                    }

                    try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
                        ImageIO.write(bufferedImage, fileExtension.toLowerCase(), outputStream);
                        byte[] imageBytes = outputStream.toByteArray();

                        long maxFileSize = 1 * 1024 * 1024 + 512 * 1024;
                        if (imageBytes.length > maxFileSize) {

                            return new AjaxResult(602, "调整后的图片大小仍超过1M，请上传更小的图片！");
                        }

                        try (ByteArrayInputStream inputStream = new ByteArrayInputStream(imageBytes)) {
                            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
                            String uniqueFileName = "uploads/" + System.currentTimeMillis() + "_" + file.getOriginalFilename();
                            try {
                                ossClient.putObject(bucketName, uniqueFileName, inputStream);
                                ossClient.setObjectAcl(bucketName, uniqueFileName, CannedAccessControlList.PublicRead);

                                String imageUrl = "https://" + bucketName + "." + endpoint + "/" + uniqueFileName;


                                com.aliyun.imagerecog20190930.Client client = createClient(accessKeyId, accessKeySecret);
                                RecognizeImageColorResponse response1 = client.recognizeImageColorWithOptions(
                                        new com.aliyun.imagerecog20190930.models.RecognizeImageColorRequest()
                                                .setUrl(imageUrl)
                                                .setColorCount(number),
                                        new com.aliyun.teautil.models.RuntimeOptions());

                                // 解析第一次返回结果
                                ObjectMapper objectMapper = new ObjectMapper();
                                JsonNode jsonNode1 = objectMapper.readTree(com.aliyun.teautil.Common.toJSONString(TeaModel.buildMap(response1)));
                                List<String> colors = extractColors(jsonNode1);

                                RecognizeImageColorResponse response2 = client.recognizeImageColorWithOptions(
                                        new com.aliyun.imagerecog20190930.models.RecognizeImageColorRequest()
                                                .setUrl(imageUrl)
                                                .setColorCount(6),
                                        new com.aliyun.teautil.models.RuntimeOptions());

                                // 解析第二次返回结果
                                JsonNode jsonNode2 = objectMapper.readTree(com.aliyun.teautil.Common.toJSONString(TeaModel.buildMap(response2)));
                                List<String> colors2 = extractColors(jsonNode2);

                                List<String> arithmeticColors = ColorUtils.generateGradientColors(colors, totalColors);
                                if (arithmeticColors.isEmpty()) {
                                    return AjaxResult.warn("获取过渡色异常");
                                }

                                Integer totalCoins1 = userCoinLogsService.getTotalCoinsByUserId(userId);

                                HashMap<Object, Object> map = new HashMap<>();
                                map.put("colors", colors);
                                map.put("colors2", colors2);
                                map.put("arithmeticColors", arithmeticColors);

                                map.put("deductAiCoins", coins);
                                map.put("totalCoins", totalCoins1);
                                map.put("deductStatus", 1);//扣除成功

                                return AjaxResult.success(map);
                            } finally {
                                if (ossClient != null) {
                                    try {
                                        ossClient.deleteObject(bucketName, uniqueFileName);

                                    } catch (Exception deleteException) {

                                    }
                                    ossClient.shutdown();
                                }
                            }
                        }
                    }
                } catch (TeaException e) {

                    return AjaxResult.error("阿里云 API 调用失败: " + e.getMessage());
                } catch (Exception e) {

                    return AjaxResult.error("上传或处理文件失败: " + e.getMessage());
                }


            }

        }

            try (InputStream fis = file.getInputStream()) {
                BufferedImage bufferedImage = ImageIO.read(fis);
                int width = bufferedImage.getWidth();
                int height = bufferedImage.getHeight();

                if (width > 1080 || height > 1080) {
                    bufferedImage = Thumbnails.of(bufferedImage)
                            .size(1080, 1080)
                            .outputQuality(0.85)
                            .asBufferedImage();
                    log.info("图片分辨率超出限制，已调整尺寸至 1080 像素以内");
                }

                try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
                    ImageIO.write(bufferedImage, fileExtension.toLowerCase(), outputStream);
                    byte[] imageBytes = outputStream.toByteArray();

                    long maxFileSize = 1 * 1024 * 1024 + 512 * 1024;
                    if (imageBytes.length > maxFileSize) {
                        log.warn("调整后的文件大小超过限制，文件大小: {} bytes", imageBytes.length);
                        return new AjaxResult(602, "调整后的图片大小仍超过1M，请上传更小的图片！");
                    }

                    try (ByteArrayInputStream inputStream = new ByteArrayInputStream(imageBytes)) {
                        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
                        String uniqueFileName = "uploads/" + System.currentTimeMillis() + "_" + file.getOriginalFilename();
                        try {
                            ossClient.putObject(bucketName, uniqueFileName, inputStream);
                            ossClient.setObjectAcl(bucketName, uniqueFileName, CannedAccessControlList.PublicRead);

                            String imageUrl = "https://" + bucketName + "." + endpoint + "/" + uniqueFileName;
                            log.info("上传文件 URL: {}", imageUrl);

                            com.aliyun.imagerecog20190930.Client client = createClient(accessKeyId, accessKeySecret);
                            RecognizeImageColorResponse response1 = client.recognizeImageColorWithOptions(
                                    new com.aliyun.imagerecog20190930.models.RecognizeImageColorRequest()
                                            .setUrl(imageUrl)
                                            .setColorCount(number),
                                    new com.aliyun.teautil.models.RuntimeOptions());

                            // 解析第一次返回结果
                            ObjectMapper objectMapper = new ObjectMapper();
                            JsonNode jsonNode1 = objectMapper.readTree(com.aliyun.teautil.Common.toJSONString(TeaModel.buildMap(response1)));
                            List<String> colors = extractColors(jsonNode1);

                            RecognizeImageColorResponse response2 = client.recognizeImageColorWithOptions(
                                    new com.aliyun.imagerecog20190930.models.RecognizeImageColorRequest()
                                            .setUrl(imageUrl)
                                            .setColorCount(6),
                                    new com.aliyun.teautil.models.RuntimeOptions());

                            // 解析第二次返回结果
                            JsonNode jsonNode2 = objectMapper.readTree(com.aliyun.teautil.Common.toJSONString(TeaModel.buildMap(response2)));
                            List<String> colors2 = extractColors(jsonNode2);

                            List<String> arithmeticColors = ColorUtils.generateGradientColors(colors, totalColors);
                            if (arithmeticColors.isEmpty()) {
                                return AjaxResult.warn("获取过渡色异常");
                            }

                            HashMap<Object, Object> map = new HashMap<>();
                            map.put("colors", colors);
                            map.put("colors2", colors2);
                            map.put("arithmeticColors", arithmeticColors);

                            map.put("deductAiCoins", 0);
                            map.put("totalCoins", totalCoins);
                            map.put("deductStatus", 0);//扣除失败

                            log.info("识别的颜色: {}", colors);
                            log.info("第二次识别的颜色: {}", colors2);

                            return AjaxResult.success(map);
                        } finally {
                            if (ossClient != null) {
                                try {
                                    ossClient.deleteObject(bucketName, uniqueFileName);
                                    log.info("已删除 OSS 中的文件: {}", uniqueFileName);
                                } catch (Exception deleteException) {
                                    log.warn("删除 OSS 文件失败: {}", deleteException.getMessage());
                                }
                                ossClient.shutdown();
                            }
                        }
                    }
                }
            } catch (TeaException e) {
                log.error("阿里云 API 调用失败: {}", e.getMessage(), e);
                return AjaxResult.error("阿里云 API 调用失败: " + e.getMessage());
            } catch (Exception e) {
                log.error("文件上传或处理失败: {}", e.getMessage(), e);
                return AjaxResult.error("上传或处理文件失败: " + e.getMessage());
            }

    }

}